﻿using System.Collections.Generic;
using System.Linq;
using Caliburn.Micro;
using SverigesRadio.SverigesRadioApp.Business;
using SverigesRadio.SverigesRadioApp.Business.Model;

namespace SverigesRadio.SverigesRadioApp.WindowsPhoneApplication.ViewModels.Channels
{
    public class DirectChannelViewModel : PropertyChangedBase,  IMainPagePivotViewModel
    {
        private IServiceCaller<Business.Model.Channels> channelService;
        private IServiceCaller<BroadcastInfo> broadCastInfoService;
        private IDictionary<string, ChannelInformationViewModel> channelInformationDictionary;

        public DirectChannelViewModel(MainPageViewModel parentViewModel)
        {
            ParentViewModel = parentViewModel;

            channelService = ParentViewModel.DataContext.GetChannelServiceCaller();
            channelService.OnServiceCallReceived += ChannelService_OnServiceCallReceived;

            broadCastInfoService = ParentViewModel.DataContext.GetBroadcastInfoServiceCaller();
            broadCastInfoService.OnServiceCallReceived += BroadcastInfoService_OnServiceCallReceived;
        }


        void ChannelService_OnServiceCallReceived(object sender, ServiceCallerEventArgs<Business.Model.Channels> e)
        {
            if (e.Error != null)
                throw e.Error;

            channelInformationDictionary = e.ServiceResult.Channel.ToDictionary(p => p.Id,
                                                                                p => new ChannelInformationViewModel(p));

            broadCastInfoService.CallAsync(SverigesRadioServices.BroadcastInformation);

        }

        private void BroadcastInfoService_OnServiceCallReceived(object sender, ServiceCallerEventArgs<BroadcastInfo> e)
        {
            foreach (var broadcastInfoChannel in
                e.ServiceResult.Channels.Where(p => channelInformationDictionary.ContainsKey(p.Id)))
            {
                channelInformationDictionary[broadcastInfoChannel.Id].AddBroadcastData(broadcastInfoChannel);
            }

            Channels = channelInformationDictionary.Select(p => p.Value).ToList();

            ParentViewModel.IsBusy = false;
        }

        private IList<ChannelInformationViewModel> channels;
        public IList<ChannelInformationViewModel> Channels
        {
            get { return channels; }
            set
            {
                channels = value;
                NotifyOfPropertyChange(() => Channels);
            }
        }

        public MainPageViewModel ParentViewModel { get; private set; }

        public void Loaded()
        {
            ParentViewModel.IsBusy = true;
            channelService.CallAsync(SverigesRadioServices.Channels);
        }
    }
}
